package com.dxyxx.framework;

/**
 * 开团吧
 */
import java.io.IOException;

import org.apache.http.Header;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.type.JavaType;

import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dxyxx.R;
import com.dxyxx.pojo.Group;
import com.dxyxx.pojo.GroupInstance;
import com.dxyxx.pojo.Product;
import com.dxyxx.pojo.ResponseResult;
import com.http.HttpUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;

/**
 * 通用的webview，只需要传入2个参数即可， param1:title 标题 param2:url 网站
 * 
 * 
 * 
 */

public class PublicWebView extends BaseActivity {
	private WebView webview;
	private ImageButton back;
	private LinearLayout public_webview_top;
	private boolean showTitle;
	private View progressBar;
	protected String baseImageURL = HttpUtil.baseApiUrl;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.public_webview);
		((ImageView) findViewById(R.id.backImageButton)).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		((ImageView) findViewById(R.id.nextImageButton)).setVisibility(View.INVISIBLE);
		TextView titleView = (TextView) findViewById(R.id.title);
		titleView.setText("开团吧");
		titleView.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
		Intent intent = getIntent();
		String url = baseImageURL + "html/group/group-index.html#/list";

		progressBar = (View) findViewById(R.id.circle);

		webview = (WebView) findViewById(R.id.public_webview_webview);
		// 加载需要显示的网页
		//		webview.setWebViewClient(new JavascriptInterface(PublicWebView.this), "name");

		webview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
		// 设置WebView属性，能够执行Javascript脚本
		webview.getSettings().setJavaScriptEnabled(true);
		// 加载需要显示的网页
		webview.loadUrl(url);
		// 设置Web视图
		webview.setWebViewClient(new MyWebViewClient());
		webview.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				if (newProgress == 100) {
					progressBar.setVisibility(View.GONE);
				} else {
					progressBar.setVisibility(View.VISIBLE);
				}
				super.onProgressChanged(view, newProgress);
			}
		});

		//		back = (ImageButton) findViewById(R.id.public_webview_back);
		//		back.setOnClickListener(new BackListener(PublicWebView.this, null, 1));

	}

	// 监听 所有点击的链接，如果拦截到我们需要的，就跳转到相对应的页面。
	private class MyWebViewClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			//三种协议：
			// ① native://order?pid=1                         ==代表单买，单买单发货,pid 代表那个product id。直接调用order/add接口
			// ② native://group?action=add&gid=1                   ==代表开团那个group团，gid代表那个团类型的id
			// ③ native://group?action=attend&groupinstanceId=1       ==代表参团。groupInstanceId代表已经被人开过团的实例id
			if (url != null && url.startsWith("native://")) {
				progressBar.setVisibility(View.VISIBLE);// 启动等待框架。
				//split 是正则表达式，使用[?] 限定是某个字符
				String kv[] = url.split("[?]")[1].split("&");
				if (url.startsWith("native://order")) {
					// 启动 单独购买页
					String productUrl = "product/get?id=" + kv[0].split("=")[1];
					HttpUtil.get(productUrl, new AsyncHttpResponseHandler() {

						@Override
						public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
							try {
								Product p = getObjectMapper().readValue(arg2, Product.class);
								Intent intent = new Intent(PublicWebView.this, GroupOrderConfirmActivity.class);
								Bundle mBundle = new Bundle();
								mBundle.putSerializable("product", p);
								mBundle.putString("type", "order");
								intent.putExtras(mBundle);
								startActivity(intent);
								//								finish();
							} catch (JsonParseException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (JsonMappingException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} finally {
								progressBar.setVisibility(View.GONE);
							}
						}

						@Override
						public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
							// TODO Auto-generated method stub

						}
					});
				}

				else if (url.startsWith("native://group?action=add")) {//我要开团
					//  根据gid 找到团详情
					String groupUrl = "group/detailsByGid?groupId=" + kv[1].split("=")[1];
					HttpUtil.get(groupUrl, new AsyncHttpResponseHandler() {

						@Override
						public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
							try {
								JavaType javaType = getObjectMapper().getTypeFactory().constructParametricType(ResponseResult.class, Group.class);
								ResponseResult<Group> rr = getObjectMapper().readValue(arg2, javaType);

								Intent intent = new Intent(PublicWebView.this, GroupOrderConfirmActivity.class);
								Bundle mBundle = new Bundle();
								Product p = rr.getObject().getProduct();
								p.setPrice(rr.getObject().getPersonPrice());
								mBundle.putSerializable("product", p);
								mBundle.putString("type", "group/add");
								mBundle.putString("groupId", rr.getObject().getId() + "");
								intent.putExtras(mBundle);
								startActivity(intent);
								//								finish();
							} catch (JsonParseException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (JsonMappingException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} finally {
								progressBar.setVisibility(View.GONE);
							}
						}

						@Override
						public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
							 

						}
					});
				} else if (url.startsWith("native://group?action=attend")) {//我要参团
					// 我要参团
					String groupUrl = "groupinstance/check?groupinstanceId=" + kv[1].split("=")[1];
					HttpUtil.get(groupUrl, new AsyncHttpResponseHandler() {

						@Override
						public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
							try {
								JavaType javaType = getObjectMapper().getTypeFactory().constructParametricType(ResponseResult.class, GroupInstance.class);
								ResponseResult<GroupInstance> rr = getObjectMapper().readValue(arg2, javaType);

								Intent intent = new Intent(PublicWebView.this, GroupOrderConfirmActivity.class);
								Bundle mBundle = new Bundle();
								Product p = rr.getObject().getGroup().getProduct();
								p.setPrice(rr.getObject().getGroup().getPersonPrice());
								mBundle.putSerializable("product", p);
								mBundle.putString("type", "group/attend");
								mBundle.putString("instaneceId", rr.getObject().getId() + "");
								intent.putExtras(mBundle);
								startActivity(intent);
								//								finish();
							} catch (JsonParseException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (JsonMappingException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} finally {
								progressBar.setVisibility(View.GONE);
							}
						}

						@Override
						public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
							// TODO Auto-generated method stub

						}
					});
				} else {
					//do nothing
				}

				//				finish();
				return true;
			}

			return super.shouldOverrideUrlLoading(view, url);
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			view.getSettings().setJavaScriptEnabled(true);
			super.onPageFinished(view, url);

		}
	}

	// 覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && webview.canGoBack()) {
			webview.goBack();// 返回前一个页面

			return true;
		} else {
			finish();

		}
		return super.onKeyDown(keyCode, event);
	}
}